    // pages/study/study.js
var WxParse = require('../../wxParse/wxParse.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    currentId:null,
    mass:null,
    screenWidth:app.globalData.screenWidth,
    screenHeight: app.globalData.screenHeight,
    tempFilePaths: '',
    tempFilePath: '',
    step:1,
    pen: 3, //画笔粗细默认值
    color: '#cc0033', //画笔颜色默认值
    hasphoto:false,
    sign:null,
    photo:null,
    photourl:null,
    signurl:null,
    sendId:null,
    canvaswidth:0,
    canvasheight:0,
    canvasMarginTop:"-100%",
    showcanvas:false,
    beginsign:false

  },
  startX: 0, //保存X坐标轴变量
  startY: 0, //保存Y坐标轴变量
  isClear: false, //是否启用橡皮擦标记
  //手指触摸动作开始
  touchStart: function(e) {
    if (this.data.step < 3) return;
    //得到触摸点的坐标
    this.startX = e.changedTouches[0].x
    this.startY = e.changedTouches[0].y
    this.context = wx.createContext()
    if (this.isClear) { //判断是否启用的橡皮擦功能  ture表示清除  false表示画画
      this.context.setStrokeStyle('#FFFFFF') //设置线条样式 此处设置为画布的背景颜色  橡皮擦原理就是：利用擦过的地方被填充为画布的背景颜色一致 从而达到橡皮擦的效果
      this.context.setLineCap('round') //设置线条端点的样式
      this.context.setLineJoin('round') //设置两线相交处的样式
      this.context.setLineWidth(20) //设置线条宽度
      this.context.save();  //保存当前坐标轴的缩放、旋转、平移信息
      this.context.beginPath() //开始一个路径
      this.context.arc(this.startX, this.startY, 5, 0, 2 * Math.PI, true);  //添加一个弧形路径到当前路径，顺时针绘制  这里总共画了360度  也就是一个圆形
      this.context.fill();  //对当前路径进行填充
      this.context.restore();  //恢复之前保存过的坐标轴的缩放、旋转、平移信息
    } else {
      this.context.setStrokeStyle(this.data.color)
      this.context.setLineWidth(this.data.pen)
      this.context.setLineCap('round') // 让线条圆润
      this.context.beginPath()
    }

  },

  //手指触摸后移动
  touchMove: function (e) {
    if(this.data.step<3)return;
    var startX1 = e.changedTouches[0].x
    var startY1 = e.changedTouches[0].y
    if (this.isClear) { //判断是否启用的橡皮擦功能  ture表示清除  false表示画画
      this.context.save();  //保存当前坐标轴的缩放、旋转、平移信息
      this.context.moveTo(this.startX, this.startY);  //把路径移动到画布中的指定点，但不创建线条
      this.context.lineTo(startX1, startY1);  //添加一个新点，然后在画布中创建从该点到最后指定点的线条
      this.context.stroke();  //对当前路径进行描边
      this.context.restore()  //恢复之前保存过的坐标轴的缩放、旋转、平移信息
      this.startX = startX1;
      this.startY = startY1;
    } else {
      this.context.moveTo(this.startX, this.startY)
      this.context.lineTo(startX1, startY1)
      this.context.stroke()
      this.startX = startX1;
      this.startY = startY1;
    }
    //只是一个记录方法调用的容器，用于生成记录绘制行为的actions数组。context跟不存在对应关系，一个context生成画布的绘制动作数组可以应用于多个
    wx.drawCanvas({
      canvasId: 'myCanvas',
      reserve: true,
      actions: this.context.getActions() // 获取绘图动作数组
    });
    this.setData({ beginsign:true});
  },

  //手指触摸动作结束
  touchEnd: function () {

  },

  canvastap:function(){
    wx.showLoading({
      title: 'canvastap'
    })
  },
  
  clearCanvas: function () {
    //重新签名
    const ctx = wx.createCanvasContext('myCanvas');
    ctx.clearRect(0, 0, 500, 300);
    ctx.draw();
    this.setData({ beginsign: false });
  },


  // 下拉刷新
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  // 页面分享

  onShareAppMessage: function () {

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      screenWidth: app.globalData.screenWidth,
      screenHeight: app.globalData.screenHeight,
      tempFilePaths: '',
      tempFilePath: '',
      step: 1,
      pen: 3, //画笔粗细默认值
      color: '#cc0033', //画笔颜色默认值
      hasphoto: false,
      photo: null
    });
    this.setData({ 
      sendId: options.sid,
      keyid: options.id
    });


  },

  chooseimage: function () {
    var that = this;
    if(!this.data.hasphoto){
      this.chooseWxImage();
    }else{
      wx.showLoading({
        title: '正在上传照片'
      })
      wx.uploadFile({
        url: app.globalData.serverPath +'api/upload-pic-two',
        filePath: this.data.photo[0],
        name: 'myfile',
        formData: {
          'lat': app.globalData.latitude,
          'lng': app.globalData.longitude
        },
        success: function (res) {
          var data = res.data
          console.log("upload photo",res);
          var urldata = JSON.parse(res.data);
          if(urldata&&urldata.url!="null"){
            that.setData({
              photourl: urldata.url,
              step: 2
            });
            wx.hideLoading();
            wx.showLoading({
              title: '加载学习内容'
            })

            wx.request({
              method: 'GET',
              url: app.globalData.serverPath + "api/bs-mass-centers/" + that.data.keyid,
              header: {
                'Authorization': app.globalData.token
              },
              success: function (res) {
                console.log("api/bs-mass-centers/", res)
                var tempmass = res.data;
                tempmass.month = tempmass.createDate.split("-")[0] + "/" + tempmass.createDate.split("-")[1];
                that.setData({ mass: tempmass });

                var articledesc = tempmass.des;
                WxParse.wxParse('articledesc', 'html', articledesc, that, 5);

                var articlecontent = tempmass.content;
                WxParse.wxParse('articlecontent', 'html', articlecontent, that, 5);
              },
              fail: function (error) {
                console.log("error", error);
              },
              complete: function () {
                wx.hideLoading();
              }

            })
          }else{//图片上传失败
            wx.showModal({
              title: '错误提示',
              content: '照片上传失败，请重试',
              showCancel:false
            })
          }
          
        }
      })
      
    }
  },

  chooseWxImage: function () {
    var that = this;
    wx.chooseImage({
      sizeType: ['original','compressed'],
      sourceType: ['camera'],
      success: function (res) {
       // console.log(res);
        var tempurl = res.tempFilePaths;
        //tempurl=tempurl.replace("http","https");
        that.setData({
          photo: tempurl,
          hasphoto:true
        })
      }
    })
  },

  finish:function(){
    var that=this;
    wx.showLoading({
      title: '正在提交数据'
    });
    wx.canvasToTempFilePath({
      canvasId: 'myCanvas',
      success: function success(res) {
        that.setData({ sign: res.tempFilePath});
        wx.uploadFile({
          url: app.globalData.serverPath + 'api/upload-pic-two',
          filePath: that.data.sign,
          name: 'myfile',
          formData: {
            'lat': app.globalData.latitude,
            'lng': app.globalData.longitude
          },
          success: function (res) {
            var data = res.data
            console.log("upload sign", res);
            var urldata=JSON.parse(res.data);
            if(urldata&&urldata.url!="null"){
              that.setData({
                signurl: urldata.url
              });
              wx.request({
                method: 'GET',
                url: app.globalData.serverPath + "/api/learn-mass-center",
                header: {
                  'Authorization': app.globalData.token,
                  'content-type': 'application/x-www-form-urlencoded'
                },
                data: {
                  sendId: that.data.sendId,
                  signUrl: that.data.signurl,
                  headUrl: that.data.photourl
                },
                success: function (res) {
                  console.log("finish!!", res);
                },
                complete: function () {
                  wx.hideLoading();
                  wx.navigateBack();
                }
              });
            }else{
              wx.showModal({
                title: '错误提示',
                content: '照片上传失败，请重试',
                showCancel: false
              })
            }
            
          }
        })
      },
      complete: function complete(e) {
        console.log(e.errMsg);
      }
    });

  },


  gotosign:function(){
    this.setData({ 
      step: 3,
      canvaswidth: 750,
      canvasheight: 500,
      canvasMarginTop:"10rpx"
      });
    
  },

  showcanvas:function(){
    this.setData({
      showcanvas: true
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
      if(app.globalData.latitude==null || app.globalData.longitude==null){
          wx.getLocation({
              type: 'wgs84',
              success: function (res) {
                  var latitude = res.latitude
                  var longitude = res.longitude
                  console.log("getlocation>>>",res);
                  app.globalData.latitude = latitude;
                  app.globalData.longitude = longitude;
              },
              fail:function(error){

              }
          })
      }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})